import type { NextApiResponse } from 'next';
import { CacheService, NewsCacheService, CategoryCacheService, UserCacheService } from '@/common/service/cache';
import R from '@/common/type/response';
import { AuthenticatedRequest, withAuth } from '@common/middleware/auth';

export async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
  if (req.method !== 'POST') {
    return R.error(res, '只支持POST请求');
  }

  try {
    const { type, id } = req.body;

    switch (type) {
      case 'all':
        // 清除所有缓存
        await CacheService.clearAll();
        R.success(res, { message: '所有缓存已清除' });
        break;

      case 'news':
        // 清除新闻缓存
        await NewsCacheService.clearNewsCache(id);
        R.success(res, { message: '新闻缓存已清除' });
        break;

      case 'category':
        // 清除分类缓存
        await CategoryCacheService.clearCategoryCache(id);
        R.success(res, { message: '分类缓存已清除' });
        break;

      case 'user':
        // 清除用户缓存
        await UserCacheService.clearUserCache(id);
        R.success(res, { message: '用户缓存已清除' });
        break;

      default:
        R.error(res, '无效的缓存类型');
    }
  } catch (error: any) {
    console.error('Redis 缓存清理错误:', error);
    R.error(res, error.message || '缓存清理失败');
  }
}

export default withAuth(handler); 